package com.qen.sheji.zhuanshiqi;

import java.util.Base64;

/**
 * 在写入文件之前，对写入的字符进行加密
 * 在读取文件的字符之后 ，对读取的字符进行解密
 */
public class EncryptionFileReaderWriter implements ReaderWriter {
    private ReaderWriter readerWriter;

    public EncryptionFileReaderWriter(ReaderWriter readerWriter) {
        this.readerWriter = readerWriter;
    }


    @Override
    public String read() {
        return decode(readerWriter.read());
    }

    @Override
    public void write(String content) {
        readerWriter.write(encode(content));
    }

    private String encode(String data) {
        var result = data.getBytes();
        for (int i = 0; i < result.length; i++) {
            result[i] += 1;
        }
        return Base64.getEncoder().encodeToString(result);
    }

    private String decode(String data) {
        var result = Base64.getDecoder().decode(data);
        for (int i = 0; i < result.length; i++) {
            result[i] -= 1;
        }
        return new String(result);
    }
}
